<template>
  <div>
    <el-popover
      placement="bottom-start"
      width="600"
      trigger="click"
      v-model="cityPickerVisible"
      popper-class="custom-city-picker-popover"
    >
      <template #reference>
        <el-button> 全国 <i class="el-icon-arrow-down"></i> </el-button>
      </template>

      <div class="city-picker-content">
        <div class="picker-header">
          <span>当前城市：全国</span>
          <i class="el-icon-close" @click="cityPickerVisible = false"></i>
        </div>

        <div class="section">
          <h4>热门城市：</h4>
          <div class="hot-cities">
            <el-tag v-for="city in hotCities" :key="city" @click="selectCity(city)">{{
              city
            }}</el-tag>
          </div>
        </div>

        <div class="section search-controls">
          <el-radio-group v-model="cityListMode" size="small">
            <el-radio-button label="province">按省份</el-radio-button>
            <el-radio-button label="city">按城市</el-radio-button>
          </el-radio-group>
          <el-input placeholder="请输入城市" v-model="searchKeyword" class="city-search-input">
            <template #prefix>
              <i class="el-icon-search"></i>
            </template>
          </el-input>
        </div>

        <div class="alphabet-nav">
          <span
            v-for="initial in alphabet"
            :key="initial"
            @click="scrollToInitial(initial)"
            :class="{ active: currentInitial === initial }"
          >
            {{ initial }}
          </span>
        </div>

        <div class="city-list-scroll-area">
          <div v-if="cityListMode === 'province'">
            <div
              v-for="initialGroup in filteredCityData"
              :key="initialGroup.initial"
              :id="`initial-${initialGroup.initial}`"
              class="province-group"
            >
              <div v-for="province in initialGroup.provinces" :key="province.name">
                <h5 class="province-name">{{ province.name }}:</h5>
                <div class="cities-container">
                  <span
                    v-for="city in province.cities"
                    :key="city"
                    @click="selectCity(city)"
                    class="city-item"
                    >{{ city }}</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div v-else>
            <p>按城市模式的内容待实现...</p>
          </div>
        </div>
      </div>
    </el-popover>
    <p>已选择: {{ selectedCity }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cityPickerVisible: false,
      selectedCity: '全国',
      hotCities: ['北京', '上海', '广州', '深圳', '重庆', '成都', '武汉', '香港', '澳门'],
      cityListMode: 'province', // 'province' 或 'city'
      searchKeyword: '',
      alphabet: ['A', 'F', 'G', 'H', 'J', 'L', 'N', 'Q', 'S', 'T', 'X', 'Y', 'Z'], // 根据您的数据调整
      currentInitial: 'A', // 用于字母导航高亮
      cityData: [
        // 示例数据，实际请从后端或高德获取
        {
          initial: 'A',
          provinces: [
            {
              name: '安徽',
              cities: [
                '合肥',
                '芜湖',
                '蚌埠',
                '淮南',
                '马鞍山',
                '淮北',
                '铜陵',
                '安庆',
                '黄山',
                '滁州',
                '阜阳',
                '宿州',
                '六安',
                '亳州',
                '池州',
                '宣城',
              ],
            },
          ],
        },
        {
          initial: 'F',
          provinces: [
            {
              name: '福建',
              cities: ['福州', '厦门', '莆田', '三明', '泉州', '漳州', '南平', '龙岩', '宁德'],
            },
          ],
        },
        {
          initial: 'G',
          provinces: [
            {
              name: '广东',
              cities: [
                '广州',
                '韶关',
                '深圳',
                '珠海',
                '汕头',
                '佛山',
                '江门',
                '湛江',
                '茂名',
                '肇庆',
                '惠州',
                '梅州',
                '汕尾',
                '河源',
                '阳江',
                '清远',
                '东莞',
                '中山',
                '潮州',
                '揭阳',
                '云浮',
              ],
            },
            {
              name: '广西',
              cities: [
                '南宁',
                '柳州',
                '桂林',
                '梧州',
                '北海',
                '防城港',
                '钦州',
                '贵港',
                '玉林',
                '百色',
                '贺州',
                '河池',
                '来宾',
                '崇左',
              ],
            },
          ],
        },
        // ... 更多数据
      ],
    }
  },
  computed: {
    filteredCityData() {
      // 这里的逻辑会根据 searchKeyword 过滤城市数据
      // 简单示例，只过滤 province 模式下的城市
      if (!this.searchKeyword) {
        return this.cityData
      }
      const keyword = this.searchKeyword.toLowerCase()
      return this.cityData
        .map((initialGroup) => {
          const filteredProvinces = initialGroup.provinces
            .map((province) => {
              const filteredCities = province.cities.filter((city) =>
                city.toLowerCase().includes(keyword),
              )
              return { ...province, cities: filteredCities }
            })
            .filter((p) => p.cities.length > 0) // 过滤掉没有匹配城市的省份
          return { ...initialGroup, provinces: filteredProvinces }
        })
        .filter((ig) => ig.provinces.length > 0) // 过滤掉没有匹配省份的字母组
    },
  },
  methods: {
    selectCity(city) {
      this.selectedCity = city
      this.cityPickerVisible = false // 选中后关闭 Popover
      // 可以在这里触发事件，将选中的城市传递给父组件
    },
    scrollToInitial(initial) {
      this.currentInitial = initial
      const element = document.getElementById(`initial-${initial}`)
      if (element) {
        // 使用 behavior: 'smooth' 获得平滑滚动效果
        element.scrollIntoView({ behavior: 'smooth', block: 'start' })
      }
    },
    // 滚动监听，用于高亮字母导航（如果需要）
    handleScroll() {
      // 实际项目中需要监听 city-list-scroll-area 的滚动事件
      // 然后计算当前视图中哪个字母开头的区域位于顶部，从而更新 currentInitial
    },
  },
  mounted() {
    // 监听滚动事件，用于字母导航的高亮
    // const scrollArea = this.$el.querySelector('.city-list-scroll-area');
    // if (scrollArea) {
    //   scrollArea.addEventListener('scroll', this.handleScroll);
    // }
  },
  beforeUnmount() {
    // 移除滚动事件监听
    // const scrollArea = this.$el.querySelector('.city-list-scroll-area');
    // if (scrollArea) {
    //   scrollArea.removeEventListener('scroll', this.handleScroll);
    // }
  },
}
</script>

<style>
/* 浮层整体样式 - 注意这里不需要 scoped，因为 popper-class 的浮层挂载在 body 下 */
.custom-city-picker-popover {
  padding: 0px !important; /* 移除 Element UI Popover 默认的内边距 */
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden; /* 确保内部内容不会溢出圆角 */
}

/* Popover 内部内容的布局 */
.city-picker-content {
  display: flex;
  flex-direction: column;
  height: 500px; /* 控制整个浮层的高度，超出滚动 */
  box-sizing: border-box;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 16px;
  font-weight: bold;
}
.picker-header .el-icon-close {
  cursor: pointer;
  font-size: 18px;
  color: #909399;
}
.picker-header .el-icon-close:hover {
  color: #409eff;
}

.section {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.hot-cities {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 标签之间的间距 */
  margin-top: 10px;
}
.hot-cities .el-tag {
  cursor: pointer;
}
.hot-cities .el-tag:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.search-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}
.city-search-input {
  flex-grow: 1; /* 让搜索框占据剩余空间 */
}

.alphabet-nav {
  display: flex;
  flex-wrap: wrap; /* 字母过多时可以换行 */
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f9f9f9;
  gap: 8px; /* 字母之间的间距 */
  font-size: 14px;
}
.alphabet-nav span {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
}
.alphabet-nav span:hover,
.alphabet-nav span.active {
  background-color: #409eff;
  color: #fff;
}

.city-list-scroll-area {
  flex: 1; /* 让城市列表区域占据剩余空间并可滚动 */
  overflow-y: auto; /* 允许垂直滚动 */
  padding: 10px 20px; /* 内部内容左右边距 */
}

.province-group {
  margin-bottom: 15px;
}
.province-name {
  font-size: 15px;
  color: #303133;
  margin-top: 0;
  margin-bottom: 10px;
  padding-left: 5px; /* 与城市对齐 */
  border-left: 3px solid #409eff; /* 左侧蓝色条 */
}

.cities-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 15px; /* 行间距和列间距 */
}
.city-item {
  cursor: pointer;
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  transition: all 0.2s;
  font-size: 14px;
  color: #606266;
}
.city-item:hover {
  border-color: #409eff;
  color: #409eff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
</style>
